<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th>
            <input type="checkbox" :checked="isAllChecked" @change="changeFn" />
            <span>全选</span>
          </th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr
          is="ShopCar"
          v-for="(item, index) in goodList"
          :key="index"
          :obj="item"
          :index="index"
          @addCount="addCountPar"
          @subCount="subCountPar"
          @delTr="delTrPar"
        ></tr>
      </tbody>
      <tfoot>
        <tr>
          <td>合计:</td>
          <td colspan="5">{{totalPrice}}</td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
import ShopCar from "./components/ShopCar.vue";
export default {
  components: {
    ShopCar,
  },
  data() {
    return {
      goodList: [
        {
          name: "诸葛亮",
          price: 1000,
          num: 1,
          checked: false,
        },
        {
          name: "蔡文姬",
          price: 1500,
          num: 1,
          checked: false,
        },
        {
          name: "妲己",
          price: 2000,
          num: 1,
          checked: false,
        },
        {
          name: "鲁班",
          price: 2200,
          num: 1,
          checked: false,
        },
      ],
    };
  },
  methods: {
    //加
    addCountPar(i) {
      this.goodList[i].num++;
    },
    //减
    subCountPar(i) {
      if (this.goodList[i].num <= 1) {
        return;
      }
      this.goodList[i].num--;
    },
    //删除
    delTrPar(i) {
      this.goodList.splice(i, 1);
    },
    //全选
    changeFn(e) {
        //全选按钮状态赋值给数组中checked属性
      this.goodList.forEach((item) => {
        return (item.checked = e.target.checked);
      });
    },
  },

  computed: {
    isAllChecked() {
      return this.goodList.every((item) => {
        return item.checked;
      });
    },
    //合计
    totalPrice() {
    //   let arr = this.goodList.filter((item) => {
    //     return item.checked == true;
    //   });
    //  return console.log(arr);
    let sum =0
    this.goodList.forEach(item=>{
        if(item.checked){
            sum+=item.price*item.num
        }
    })
    return sum
    },
  },
};
</script>

<style>
</style>